package xyz.longicorn.driver.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.generator.RandomGenerator;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import xyz.longicorn.driver.dto.ApiResult;
import xyz.longicorn.driver.dto.ShareDto;
import xyz.longicorn.driver.pojo.ShareInfo;
import xyz.longicorn.driver.service.ShareService;
import xyz.longicorn.driver.service.UserService;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/share")
public class ShareController {
    @Resource
    private ShareService shareService;
    @Resource
    private UserService userService;

    /**
     * 创建分享
     *
     * @return
     */
    @RequestMapping("/create")
    public ApiResult create(@RequestBody ShareInfo info) {
        String id = StpUtil.getLoginId().toString();
        // 设置分享者
        info.setUid(Integer.parseInt(id));
        // 设置密码
        if ("yes".equalsIgnoreCase(info.getPassword())) {
            RandomGenerator generator = new RandomGenerator("0123456789abcdefg", 4);
            info.setPassword(generator.generate());
        } else {
            info.setPassword(null); // 不需要密码
        }
        info.setId((new RandomGenerator(10)).generate());
        return ApiResult.success(shareService.create(info));
    }

    @RequestMapping("/info")
    public ApiResult info(String id) {
        final ShareInfo shareInfo = shareService.getById(id);
        if (shareInfo == null) {
            return ApiResult.error(1, "分享码不正确或分享已过期");
        }
        ShareDto share = new ShareDto();
        share.setShare(shareInfo);
        share.setUser(
                userService.getById(
                shareInfo.getUid()
        ));
        return ApiResult.success(share);
    }

    @RequestMapping("/list")
    public ApiResult list(@RequestParam(required = true) String id, String parent, String password) {
        // 在控制器中全部 响应正确的结果
        return ApiResult.success(shareService.listFiles(id, parent, password));
    }

}
